# this script generates measures of defensive ownership based on JSCReg:
# foreign in chain; offshore in chain
# (JSCReg does not allow to identify oligarch in chain)

# load the list of countries designated as offshores
offshore_codes <- read_csv("Additional Data/offshore_codes.csv")

# create a list of all foreign firms in the extracted ownership links
foreign_firms <- all.ids %>% 
  filter(entity == "corporate", country != 804) %>% 
  pull(id) %>% unique()
foreign_firms_codes <- all.ids %>%
  filter(entity == "corporate" & country != 804) %>%
  select(id, country, entity_name)

# create a list of the main oligarch-controlled firms;
# we will check all other entities for ownership links with these firms
step0_firms <- all.ids %>%
  filter(step == 0) %>%
  pull(id)

# create a data frame that will be populated with defensive ownership measures
# for the main oligarch-controlled firms
DUP_firms <- read_dta("Delo_UP.dta") %>%
  rename(entity_name = name) %>%
  select("okpo", "entity_name", "group", group_list) %>%
  mutate(id = paste0("UC", okpo),
         shortest_path_foreign = NA,
         foreign_owners = NA,
         foreign_entities_countries = NA) %>%
  # exclude firms that are not found in JSCReg
  filter(id %in% step0_firms)

# create a data frame that will be populated with data on foreign owners
# (used in some supplementary analyses)
DUP_foreign_owners <- tibble(okpo = as.numeric(), 
                             foreign_owner_name = as.character(), 
                             foreign_owner_country = as.numeric())

# examine paths to oligarch-controlled firms from foreign firms
for (i in 1:nrow(DUP_firms)) {
  firm <- DUP_firms$id[i]
  print(paste(i, firm))
  
  # extract paths from foreign firms
  spaths_foreign <- shortest_paths(o.network.D, firm, 
                                   foreign_firms, 
                                   mode = "in")

  # calculate the length of paths to foreign firms
  shortest_path_foreign <- unlist(lapply(spaths_foreign$vpath, length))
  shortest_path_foreign <- 
    ifelse(max(shortest_path_foreign) > 0,
           min(shortest_path_foreign[shortest_path_foreign != 0]-1),
           NA)
  DUP_firms$shortest_path_foreign[i] <- shortest_path_foreign
  
  # when path exists, set foreign in chain to 1
  DUP_firms$foreign_in_chain[i] <- 1 - is.na(shortest_path_foreign)
  
  # if any of the foreign entities in chain are offshore,
  # set offshore in chain to 1
  foreign_entities <- unique(unlist(lapply(spaths_foreign$vpath, names)))
  foreign_entities <- foreign_entities[foreign_entities %in% foreign_firms]
  foreign_entities_countries <- foreign_firms_codes %>%
    filter(id %in% foreign_entities) %>% 
    pull(country) %>% unique()
  DUP_firms$offshore_in_chain[i] <- 
    sum(any(foreign_entities_countries %in% offshore_codes$country_code))
  
  # save all countries of foreign entities in chain
  DUP_firms$foreign_entities_countries[i] <- paste(foreign_entities_countries,
                                                   collapse = "|")
  
  # update the data frame with foreign owners
  if (length(foreign_entities) > 0) {
    firm_foreign_owners <- tibble(okpo = as.numeric(substr(firm, 3, nchar(firm))),
                                  id = foreign_entities) %>%
      left_join(foreign_firms_codes) %>%
      select(-id) %>%
      rename(foreign_owner_name = entity_name,
             foreign_owner_country = country)
    DUP_foreign_owners <- bind_rows(DUP_foreign_owners, firm_foreign_owners)
  }
}

# add dummy: whether a firm has owners in the network graph
has_owners <- DUP_firms %>%
  select(id) %>%
  mutate(has_owners = if_else(id %in% all.edges$sub, 1, 0))
DUP_firms <- left_join(DUP_firms, has_owners)

# add oligarch-controlled firms not in the network
DUP_not_in_network <- read_dta("Delo_UP.dta") %>%
  select("okpo", "name", "group", group_list) %>%
  filter(!(okpo %in% DUP_firms$okpo)) %>%
  rename(entity_name = name) %>%
  mutate(has_owners = 0)
DUP_firms <- bind_rows(DUP_firms, DUP_not_in_network)

# add dummy: whether oligarch-controlled firms are present in JSCReg 
# (affects the composition of the sample later)
J_presence <- read_dta(paste0("Ownership Data/Delo_UP_present_JSCReg_SReg_", 
                              search_date, ".dta")) %>%
  select(okpo, present_JSCReg)
DUP_firms <- left_join(DUP_firms, J_presence)

# set foreign in chain/offshore in chain to NA if firm not present in JSCReg
DUP_firms <- DUP_firms %>%
  mutate(foreign_in_chain = as.numeric(foreign_in_chain),
         offshore_in_chain = as.numeric(offshore_in_chain),
         foreign_in_chain = case_when(
           present_JSCReg == 0 ~ NA_real_,
           present_JSCReg == 1 & is.na(foreign_in_chain) ~ 0,
           TRUE ~ foreign_in_chain
         ),
         offshore_in_chain = case_when(
           present_JSCReg == 0 ~ NA_real_,
           present_JSCReg == 1 & is.na(offshore_in_chain) ~ 0,
           TRUE ~ offshore_in_chain
         )) %>%
  select(-c(id, foreign_owners))

# save data
write_dta(DUP_firms, paste0("Network Data/DUP_hiding_", search_date, 
                            "_JSCReg_only.dta"))
write_dta(DUP_foreign_owners, paste0("Network Data/DUP_foreign_owners_", 
                                     search_date, "_JSCReg_only.dta"))
